import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:im_app/im/page/view/component/UiUtil.dart';
import 'package:im_app/im/util/ImConstant.dart';
import 'package:im_app/im/util/UiUtil.dart';

import '../../pojo/ImPojo.dart';
import '../../socket/dto/business/WebRtcData.dart';
import '../bloc/WebRtcCubit.dart';
import 'WebRtcFloatingView.dart';
import 'component/LButton.dart';
import 'component/UserIconView.dart';

/// invitationReq 为null时，表示用户主动发起视频聊天
/// invitationReq 不为null时， 表示用户被邀请视频聊天
class WebRtcVideoView extends StatelessWidget {

  OverlayEntry? overlayEntry = null;
  final WebRtcInvitationReq? invitationReq;

  WebRtcVideoView({ this.invitationReq, super.key});

  @override
  Widget build(BuildContext context) {
    var webRtcCubit = context.watch<WebRtcCubit>();
    return GestureDetector(
        onHorizontalDragEnd: (details) {
          if (details.velocity.pixelsPerSecond.dx > 200) { // 左滑检测
            webRtcCubit.add(WebRtcSwitchScreenSmallEvent());
          }
        },
      child: PopScope(onPopInvokedWithResult: (bool didPop, dynamic result){
        webRtcCubit.add(WebRtcSwitchScreenSmallEvent());
      }, child: buildBody(context, webRtcCubit),),
    );
  }

  Widget buildBody(BuildContext context, WebRtcCubit webRtcCubit) {
    if (webRtcCubit.state.isScreenSmall) {
      return Stack(
        children: [
          _buildMainView(context, webRtcCubit),
        ],
      );
    } else {
      return Container(
        color: Colors.black,
        child: Stack(
          children: [
            _buildMainView(context, webRtcCubit),
            _buildTitlePane(context, webRtcCubit),
            _buildLocalView(context, webRtcCubit),
            if (webRtcCubit.state.isAccept && !webRtcCubit.state.isAccepted)
              _buildAcceptPane(context, webRtcCubit),

            if (!webRtcCubit.state.isAccept || webRtcCubit.state.isAccepted)
              _buildControlPane(context, webRtcCubit),
          ],
        ),
      );
    }
  }

  // 对方视频
  Widget _buildMainView(BuildContext context, WebRtcCubit webRtcCubit) {
    var state = webRtcCubit.state;
    var mediaList = state.mediaList;
    if (state.isScreenSmall) {
      if(mediaList.isNotEmpty) {
        var connectedMediaList = state.mediaList.where((media)=>media.status == WebRtcUserDataStatus.connected).toList();
        if (connectedMediaList.isNotEmpty) {
          var child = RTCVideoView(
            mediaList[0].videoRenderer?? RTCVideoRenderer(),
            mirror: true,
            objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
          );
          return WebRtcFloatingView(child: child, onTapFunction: () {
            webRtcCubit.add(WebRtcSwitchScreenSmallEvent());
          });
        } else {
          var mediaData = state.mediaList[0];
          return _buildUserIcon(context, mediaData.user);
        }
      } else {
        return const Text('');
      }
    }
    if (mediaList.isNotEmpty) {
      return _buildMediaPane(context, webRtcCubit);
    } else {
      return const Text('');
    }
  }

  Widget _buildLocalView(BuildContext context, WebRtcCubit webRtcCubit) {
    var state = webRtcCubit.state;
    var mediaList = state.mediaList.where((media)=>media.status == WebRtcUserDataStatus.connected).toList();
    if (mediaList.isNotEmpty) { // 构建浮层视频框
      return WebRtcFloatingView(child: state.localMediaData == null ? const Text('') : RTCVideoView(
        state.localMediaData?.videoRenderer?? RTCVideoRenderer(),
        mirror: true,
        objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
      ),);
    } else {  // 构建本地视频框
      return RTCVideoView(
        state.localMediaData?.videoRenderer?? RTCVideoRenderer(),
        mirror: true,
        objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
      );
    }
  }

  Widget _buildTitlePane(BuildContext context, WebRtcCubit webRtcCubit) {
    return Padding(padding: const EdgeInsets.only(top: 80, left: 50), child: Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        GestureDetector(
          onTap: (){
            if (webRtcCubit.state.mediaList.where((media)=>media.status == WebRtcUserDataStatus.connected).isNotEmpty) {
              webRtcCubit.add(WebRtcSwitchScreenSmallEvent());
            }
          },
          child: buildSvgView('assets/webrtc-img/screen_small.svg', 30, 30, Colors.white),
        ),
      ],
    ),);
  }

  // 构建接受面板
  Widget _buildAcceptPane(BuildContext context, WebRtcCubit webRtcCubit) {
    return Positioned(
        top: 150,
        left: 10,
        right: 10,
        bottom: 60,
        child: Column(
          children: [
            _buildTipPane(context, webRtcCubit),                             // 连接提示信息栏
            const SizedBox(height: 80,),
            _buildAcceptOrRejectPane(context, webRtcCubit),                                      // 设置栏： 麦克风，扬声器， 摄像头
          ],
        ));
  }

  Widget _buildControlPane(BuildContext context, WebRtcCubit webRtcCubit) {
    return Positioned(
        top: 100,
        left: 10,
        right: 10,
        bottom: 60,
        child: Column(
          children: [
            _buildTipPane(context, webRtcCubit),                             // 连接提示信息栏
            const SizedBox(height: 40,),
            _buildSettingPane(context),                                      // 设置栏： 麦克风，扬声器， 摄像头
            const SizedBox(height: 30,),
            _buildClosePane(context, webRtcCubit),                           // 关闭控制行
          ],
        ));
  }

  Widget _buildMediaPane(BuildContext context, WebRtcCubit webRtcCubit) {
    var state = webRtcCubit.state;
    var loginUserId = UiUtil.getLoginUser().userId;
    var mediaList = state.mediaList.where((media)=>media.status != WebRtcUserDataStatus.offline
        && media.user.userId != loginUserId).toList();

    if (mediaList.length == 1) {
      var mediaData = mediaList[0];
      if (mediaData.status == WebRtcUserDataStatus.connected) {
        return RTCVideoView(
          mediaData.videoRenderer!,
          mirror: true,
          objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
        );
      } else {
        var user = mediaList[0].user;
        return Center(child: _buildUserIcon(context, user),);
      }
    }

    var column = calcMediaColumn(mediaList);

    return Padding(padding: const EdgeInsets.only(top: 90), child: GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: column, childAspectRatio: 0.9, crossAxisSpacing: 0.0, mainAxisSpacing: 0.0),
      shrinkWrap: true,
      itemCount: mediaList.length,
      itemBuilder: (BuildContext context, int index) {
        var mediaData = mediaList[index];
        if (mediaData.status == WebRtcUserDataStatus.connected) {
          return _buildMediaView(mediaData);
        } else {
          var user = state.mediaList[index].user;
          return Center(child: _buildUserIcon(context, user),);
        }
      },
    ),);
  }

  // 用户头像
  Widget _buildUserIcon(BuildContext context, ImUser? user) {
    if (user != null) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          UserIconView(user: user, iconSize: 120,),
          const SizedBox(
            height: 10,
          ),
          Text(user.userName ?? user.userId,
            style: const TextStyle(decoration: TextDecoration.none, fontSize: 20, color: Colors.white),)
        ],
      );
    } else {
      return const Text('');
    }
  }

  Widget _buildTipPane(BuildContext context, WebRtcCubit webRtcCubit) {
    var mediaList = webRtcCubit.state.mediaList.where((media)=>media.status == WebRtcUserDataStatus.connected).toList();
    var isAccept = webRtcCubit.state.isAccept;
    var message = mediaList.isEmpty ? (isAccept ? '对方邀请您视频通话': '等待对方接受连接...') : '';
    return Expanded(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [Text(message, style: const TextStyle(color: Colors.white30, fontSize: 20,
              decoration: TextDecoration.none),)],
        )
    );
  }

  Widget _buildSettingPane(BuildContext context) {
    var webRtcCubit = context.read<WebRtcCubit>();
    var state = webRtcCubit.state;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        LButton(
          name: state.isCloseAudio ? '麦克风已关' : '麦克风已开',
          assetImage: state.isCloseAudio ? 'assets/webrtc-img/audio_close.svg' : 'assets/webrtc-img/audio.svg',
          textColor: Colors.white,
          itemFocusColor: Colors.white24,
          selectCallback: () {
            webRtcCubit.add(WebRtcSwitchAudioEvent());
          },
        ),
        LButton(
          name: '扬声器已开',
          assetImage: 'assets/webrtc-img/speaker.svg',
          textColor: Colors.white,
          itemFocusColor: Colors.white24,
          selectCallback: () { },
        ),
        LButton(
          name: state.isCloseVideo ? '摄像头已关' : '摄像头已开',
          assetImage: state.isCloseVideo ? 'assets/webrtc-img/camera_close.svg' : 'assets/webrtc-img/camera.svg',
          textColor: Colors.white,
          itemFocusColor: Colors.white24,
          selectCallback: () {
            webRtcCubit.add(WebRtcSwitchVideoEvent());
          },
        )
      ],
    );
  }

  Widget _buildClosePane(BuildContext context, WebRtcCubit webRtcCubit) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        GestureDetector(
          onTap: () {
            webRtcCubit.add(WebRtcCloseEvent(context));
          },
          child: const CircleAvatar(
            radius: 30,
            backgroundColor: Colors.red,
            child: Icon(
              Icons.close,
              size: 30,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildAcceptOrRejectPane(BuildContext context, WebRtcCubit webRtcCubit) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        LButton(
          name: '接受',
          assetImage: 'assets/webrtc-img/calling.svg',
          itemBackgroundColor: Colors.green,
          radius: 50,
          textColor: Colors.white,
          itemFocusColor: Colors.white24,
          selectCallback: () {
            var screenWidth = MediaQuery.of(context).size.width; // 获取屏幕宽度
            var screenHeight = MediaQuery.of(context).size.height; // 获取屏幕高度
            webRtcCubit.add(WebRtcAcceptInvitationEvent(invitationReq!, context, screenWidth, screenHeight));
          },
        ),

        LButton(
          name: '拒绝',
          assetImage: 'assets/webrtc-img/close.svg',
          itemBackgroundColor: Colors.red,
          radius: 50,
          textColor: Colors.red,
          itemFocusColor: Colors.grey,
          selectCallback: () {
            webRtcCubit.add(WebRtcRejectInvitationEvent(invitationReq!, context));
          },
        ),
      ],
    );
  }

  Widget _buildMediaView(WebRtcUserData mediaData) {
    var name = mediaData.user.userName ?? mediaData.user.userId;
    return Stack(
      alignment: AlignmentDirectional.center,
      children: [
        RTCVideoView(
          mediaData.videoRenderer!,
          mirror: true,
          objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
        ),
        Positioned(bottom: 5, child: Text(name, style:
          const TextStyle(color: Colors.red, fontSize: ImConstant.IM_DEFAULT_SIZE, decoration: TextDecoration.none)))
      ],);
  }

  int calcMediaColumn(List<WebRtcUserData> mediaList) {
    if (mediaList.length < 5) return 2;
    if (mediaList.length < 9) return 3;
    return 3;
  }

}

